package com.me.blood.frag;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.me.blood.BuildConfig;
import com.me.blood.R;
import com.me.blood.activity.BaseActivity;
import com.me.blood.activity.FeedbackActivity;
import com.me.blood.activity.WebActivity;
import com.me.blood.databinding.FragMeBinding;
import com.me.utils.Constant;
import com.me.utils.ToastUtil;
import com.me.utils.Utils;
import com.me.ad.ADType;

public class MeFragment extends BaseTabFragment {

    FragMeBinding binding;
    FrameLayout container;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragMeBinding.inflate(inflater, container, false);
        binding.desc.setText("欢迎使用" + getString(R.string.app_name));
        binding.ver.setOnClickListener(v -> ToastUtil.showShortToast("当前版本" + BuildConfig.VERSION_NAME));
        binding.agree.setOnClickListener(v -> WebActivity.launch(getActivity(), Constant.AGREE));
        binding.privacy.setOnClickListener(v -> WebActivity.launch(getActivity(), Constant.PRIVACY));
        binding.feed.setOnClickListener(v -> {
            Intent i = new Intent(getActivity(), FeedbackActivity.class);
            startActivity(i);
        });
        binding.us.setOnClickListener(v -> {
            toEmail();
        });
        return binding.getRoot();
    }

    @Override
    protected void loadData() {
        super.loadData();
        showFeed();
    }

    @Override
    protected ADType getXpType() {
        return ADType.XP;
    }

    private void showFeed() {
        if (binding.frame.getWidth() <= 0) {
            h.postDelayed(this::showFeed, 200);
            return;
        }
        int w = binding.frame.getWidth();
        int h = binding.frame.getHeight();
        if (w >= 2 * h) {
            w = 2 * h;
        } else {
            h = w / 2;
        }
        if (container == null) {
            container = new FrameLayout(getActivity());
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(w, h);
            params.gravity = Gravity.CENTER;
            binding.frame.addView(container, params);
        }
        if (container.getChildCount() == 0) {
            ((BaseActivity) getActivity()).getFeed(container, w);
        }
    }

    private void toEmail() {
        try {
            Intent data = new Intent(Intent.ACTION_SENDTO);
            data.setData(Uri.parse("mailto:shshkj8888@163.com"));
            startActivity(data);
        } catch (Throwable e) {
            Utils.copy("shshkj8888@163.com");
            ToastUtil.showShortToast("已复制到剪贴板");
        }
    }
}
